<template>
	<s-layout @loginEnd="loginEnd"  navbar="custom1" :bgStyle="{
	 color: '#F8F8F8'
	}" onShareAppMessage>
		<assNavbar :title="state.type==0?'商户入驻':'代理商户入驻'" :background="{img: 'none',BGcolor: '#fff'}"></assNavbar>
		
		
		
		
		<view class="form-box ss-p-24 " >
			<!-- <view v-if="state.disabled&&!state.seeAccount" style="color:#515151">
				<view class="ss-flex justify-between font-1">
					<view style="color:#003288;font-weight:bold">待审核</view>
					<view>2025-10-13 12:00:34</view>
				</view>
				<view class="ss-m-y-20">驳回原因xxx</view>
			</view> -->
			<view>
				<uni-forms ref="form" :modelValue="state.form" :rules="rules" label-width="90">
					<!-- <view class="ss-m-b-20" v-if="!state.seeAccount" style="background-color: #fff;border-radius: 20rpx;">
						<view 
						@tap="sheep.$router.go('/pages/commission/merchant/surpriseForm',{type:state.type})"
						class="ss-flex justify-between ss-p-x-30 ss-p-y-20">
							<view>前往鲸喜商户入驻</view>
							<uni-icons type="right" size="22" color="#BCBCBC"></uni-icons>
						</view>
						
					</view> -->
					<view v-if="!state.seeAccount" style="padding:40rpx 30rpx;background-color: #fff;border-radius: 20rpx;">
						<!-- 邀请人信息从已入驻的资料中获取，禁止修改 -->
						<view class="form-box-head-title">邀请人信息</view>
						<!-- <uni-forms-item label="邀请人类型" name="role" required>
							<view class="form-box-input-item">
								<input :disabled="true" type="text" v-model="state.form.role" placeholder="" />
							</view>
						</uni-forms-item> -->
						<uni-forms-item label="邀请人姓名" name="agency_name" >
							<view class="form-box-input-item">
								<input :disabled="true" type="text" v-model="state.form.agency_name" placeholder="" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="邀请人手机号码" name="agency_mobile" >
							<view class="form-box-input-item">
								<input :disabled="true" type="number" :maxlength="11" v-model="state.form.agency_mobile" placeholder="" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="商户类型" name="serve" required>
							<view class="form-box-input-item">
								<radio-group  @change="radioChange" class="ss-flex flex-wrap font-1 ss-p-t-14"  style="width:370rpx;color:#424242">
									<label class="uni-list-cell uni-list-cell-pd ss-flex ss-m-l-10" v-for="(item, index) in radioFormList" :key="item.value">
											<radio color="#003288" :disabled="edited" style="transform: scale(0.5)" :value="item.value" :checked="state.form.serve == item.value" />
										<view class="font-1" style="color:gray">{{item.label}}</view>
									</label>
								</radio-group>
							</view>
						</uni-forms-item>
					</view>
					
					
					<view v-if="!state.seeAccount" class="ss-m-t-20 bg-white"  style="padding:40rpx 30rpx;border-radius: 20rpx;">
						<view class="form-box-head-title">商户信息</view>
						<uni-forms-item label="商户姓名" name="name" required>
							<view class="form-box-input-item">
								<input :disabled="state.disabled"  type="text" v-model="state.form.name" placeholder="请输入商户姓名" @input="setValue($event,'name')"/>
							</view>
						</uni-forms-item>
						<uni-forms-item label="商户手机号码" name="mobile" required>
							<view class="form-box-input-item">
								<input :disabled="state.disabled" type="number" :maxlength="11" v-model="state.form.mobile" placeholder="请输入手机号码" @input="setValue($event,'mobile')"/>
							</view>
						</uni-forms-item>
						
						<uni-forms-item label="商户名称" name="merchant_name" required>
							<view class="form-box-input-item">
								<input :disabled="state.disabled" type="text" v-model="state.form.merchant_name" placeholder="请输入商户名称" @input="setValue($event,'merchant_name')"/>
							</view>
							<!-- <view class="form-box-input-item" @click="state.showRegion=true">
								<view style="font-size:32rpx;">{{ state.address_txt || '请选择城市' }}</view>
								<uni-icons type="forward" size="22" color="#999999"></uni-icons>
							</view> -->
						</uni-forms-item>
						
						<uni-forms-item label="商户位置" name="address" required>
							<view class="form-box-input-item">
								<input :disabled="state.disabled" type="text" v-model="state.form.address" placeholder="请输入商户位置" @input="setValue($event,'address')"/>
							</view>
						</uni-forms-item>
						
					</view>
					
					
					<view v-if="!state.seeAccount" class="ss-m-t-20 bg-white" style="padding:40rpx 30rpx;border-radius: 20rpx;">
						<view class="form-box-head-title"><span style="color:#ED1010">*</span>法人实名认证</view>
						
						<uni-forms-item  name="reverse_card" >
							<view class="form-box-input-item-left ss-flex justify-between" >
								<s-uploader 
								:sizeType="['original']"
								 :disabled="state.disabled"
								fileMediatype="image"
								v-model:url="state.form.reverse_card" 
								:limit="1" 
								:listStyles="{border:false}"
								:imageStyles="{ width: '300rpx', height: '300rpx' }">
									<image style=" width: 300rpx" 
									:src="sheep.$url.cdn('/storage/giveaway/20250315/85e929c2b8c18b2221bb4c6798e94402.png')" 
									mode="widthFix" />
								</s-uploader>
								<s-uploader :sizeType="['original']" :disabled="state.disabled" v-model:url="state.form.protrait_card" :limit="1" :imageStyles="{ width: '300rpx', height: '300rpx' }">
									<image style=" width: 300rpx;border-radius:20rpx"
									:src="sheep.$url.cdn('/storage/giveaway/20250315/4b254833607e2d10789529f46a18e248.png')" 
									mode="widthFix" />
								</s-uploader>
							</view>
						</uni-forms-item>
					</view>
					
					<view v-if="!state.seeAccount" class="ss-m-t-20 bg-white" style="padding:40rpx 30rpx;border-radius: 20rpx;">
						<view class="form-box-head-title"><span style="color:#ED1010">*</span>营业执照备案</view>
						
						<uni-forms-item  name="business_license" >
							<view class="ss-flex justify-between"  >
								<s-uploader  :disabled="state.disabled"
								style="margin-top:-40rpx"
								fileMediatype="image"
								v-model:url="state.form.business_license" 
								:limit="1" 
								:sizeType="['original']"
								:listStyles="{border:false}"
								:imageStyles="{ width: '800rpx',height:'400rpx'}">
									<image  style=" width: 800rpx;border-radius:20rpx" 
									:src="sheep.$url.cdn('/storage/giveaway/20250315/42128206c05f913c917c46a43371644a.png')" 
									mode="widthFix" />
								</s-uploader>
							</view>
						</uni-forms-item>
					</view>
					<view v-if="!state.seeAccount" class="ss-m-t-20 bg-white" style="padding:40rpx 30rpx;border-radius: 20rpx;">
						<view class="form-box-head-title"><span style="color:#ED1010">*</span>店铺照片</view>
						<view class="ss-p-l-24">
							<uni-forms-item  name="shop_image" >
									<view class="ss-flex " style="flex-wrap: wrap;">
										<view class="ss-m-10">
											<s-uploader
											 :disabled="state.disabled"
											fileMediatype="image"
											v-model:url="state.image1" 
											:limit="1" 
											:sizeType="['original']"
											:listStyles="{border:false}"
											:imageStyles="{ width: '300rpx', height: '300rpx' }">
												<view class="morePic">
													店内照片
												</view>
											</s-uploader>
										</view>
										<view class="ss-m-10">
											<s-uploader 
											 :disabled="state.disabled"
											fileMediatype="image"
											v-model:url="state.image2" 
											:limit="1" 
											:sizeType="['original']"
											:listStyles="{border:false}"
											:imageStyles="{ width: '300rpx', height: '300rpx' }">
												<view class="morePic">
													店内照片
												</view>
											</s-uploader>
										</view>
										<view class="ss-m-10">
											<s-uploader 
											 :disabled="state.disabled"
											fileMediatype="image"
											v-model:url="state.image3" 
											:limit="1" 
											:sizeType="['original']"
											:listStyles="{border:false}"
											:imageStyles="{ width: '300rpx', height: '300rpx' }">
												<view class="morePic">
													门头照片
												</view>
											</s-uploader>
										</view>
										<view class="ss-m-10">
											<s-uploader 
											 :disabled="state.disabled"
											fileMediatype="image"
											v-model:url="state.image4" 
											:limit="1" 
											:sizeType="['original']"
											:listStyles="{border:false}"
											:imageStyles="{ width: '300rpx', height: '300rpx' }">
												<view class="morePic">
													收银台照片
												</view>
											</s-uploader>
										</view>
										<view class="ss-m-10">
											<s-uploader
											 :disabled="state.disabled"
											fileMediatype="image"
											v-model:url="state.image_more" 
											:limit="100" 
											:sizeType="['original']"
											:imageStyles="{ width: '300rpx', height: '300rpx' }">
												<view class="morePic">
													更多照片
												</view>
											</s-uploader>
										</view>
										
									</view>
									
								</uni-forms-item>
							
						</view>
					
					</view>
					
					<template v-if="state.seeAccount">
						<!-- 商家账号信息 -->
						<view class="ss-m-t-20 bg-white" style="padding:33rpx 26rpx 34rpx 37rpx;border-radius: 20rpx;">
							<view class="form-box-head-title ss-m-b-24">商家账号信息</view>
							<view style="line-height:1.5em;color: #383838;">
								<view>账号：{{state.accountInfo.account}}</view>
								<view>密码：{{state.accountInfo.password}}</view>
								<view>系统地址：{{state.accountInfo.website}}</view>
							</view>
							<view class="ss-flex justify-end">
								<button class="btn2 ss-reset-button " @tap="onCopy">
									复制
								</button>
							</view>
						</view>
						
						<!-- 支付码 -->
						<view v-if="state.accountInfo.pay_qrcode" class="ss-m-t-20 bg-white" style="padding:33rpx 26rpx 34rpx 37rpx;border-radius: 20rpx;">
							<view class="form-box-head-title ss-m-b-24">支付码</view>
							<image class="ss-flex justify-center" style=" width: 300rpx;height:300rpx;margin:0 auto"
							:src="sheep.$url.cdn(state.accountInfo.pay_qrcode)" 
							/>
							<view class="ss-flex justify-end">
								<button class="btn2 ss-reset-button " @tap="handleSave(sheep.$url.cdn(state.accountInfo.pay_qrcode))">
									下载
								</button>
							</view>
						</view>
					</template>
					
					
					<view style="height:300rpx"></view>
				</uni-forms>
			</view>
		</view>
		
		<su-fixed bottom v-if="!state.seeAccount">
			<view class="bg-white ss-p-t-20 ss-p-b-60 ss-flex justify-center">
				<!-- <button v-if="state.type==1" style="width:320rpx;margin-right:20rpx" class="btn ss-reset-button " @tap="submit()">
					 保存草稿
				</button> -->
				<!-- :style="{width:state.type==1?'320rpx':''}" -->
				<button  class="btn ss-reset-button " @tap="submit()">
					提交
				</button>
			</view>
			
		</su-fixed>
		
	</s-layout>
	
	
	<!-- 地址选择弹窗 -->
	<!-- <su-region-picker :show="state.showRegion" @cancel="state.showRegion = false" @confirm="onRegionConfirm" /> -->

</template>

<script setup>
	import assNavbar from '@/components/ass-navbar.vue';
	import $store from '@/sheep/store';
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import Test from "@/sheep/helper/test.js";
	import {
		showAuthModal,
	} from '@/sheep/hooks/useModal';
	import {
		ref,
		computed,
		reactive
	} from 'vue';
	import sheep from '@/sheep';
	import  { clone } from 'lodash'
	
	const radioList=[
		{value:2,label:'本地生活'},
		{value:1,label:'电商商家'},
		{value:3,label:'鲸喜生活圈'},
	];
	
	const radioFormList = computed(()=>{
		if(state.form.serve==1){
			return [{value:1,label:'电商商家'}];
		}else if(state.form.serve==2){
			return [{value:2,label:'本地生活'}];
		}else if(state.form.serve==3){
			return [{value:3,label:'鲸喜生活圈'}];
		}else if(state.form.serve==10){
			return [{value:10,label:'供应链'}];
		}else{
			return [{value:2,label:'本地生活'},{value:1,label:'电商商家'},{value:3,label:'鲸喜生活圈'}];
		}
	});
	
	const edited = computed(()=>{
		return state.form.serve?false:true;
	})
	
	const form = ref(null);
	
	
	// 数据
	const state = reactive({
		type:0,//0商家自己入驻   1代理帮商家入驻
		showRegion:false, 
		form:{
			shop_image:'',//店铺照片
			reverse_card:'',//身份证正面
			protrait_card:'',//身份证反面
			business_license:'',
			serve:null,//商户类型
			name:null,
			mobile:null,
			merchant_name:null,
			address:null,
			
		},
		address_txt:'',
		disabled:false,
		userInfo:{},
		seeAccount:false,//是否是查看账号
		accountInfo:{},//账号信息
		image1:'',
		image2:'',
		image3:'',
		image4:'',
		image_more:''
		
	});
	// 复制
	const onCopy = () => {
	  sheep.$helper.copyText(
		`账号：${state.accountInfo.account};密码：${state.accountInfo.password};系统地址：${state.accountInfo.website}`
	  );
	};
	
	const rules = {
		// 对name字段进行必填验证
		name: {rules: [{required: true,errorMessage: '请填写姓名',}]},
		role: {rules: [{required: true,errorMessage: '请填写',}]},
		// agency_name: {rules: [{required: true,errorMessage: '请填写代理人姓名',}]},
		// agency_mobile: {rules: [{required: true,errorMessage: '请填写代理人手机号',}]},
		reverse_card: {rules: [{required: true,errorMessage: '请选择',}]},
		protrait_card: {rules: [{required: true,errorMessage: '请选择',}]},
		business_license: {rules: [{required: true,errorMessage: '请选择',}]},
		merchant_name: {rules: [{required: true,errorMessage: '请填写商户名称',}]},
		address: {rules: [{required: true,errorMessage: '请填写商户地址',}]},
		mobile: {
			rules: [{
				required: true,
				errorMessage: '请输入联系电话',
			},{
				validateFunction: (rule, value, data, callback) => {
					// 异步需要返回 Promise 对象
					return new Promise((resolve, reject) => {
						if (Test.mobile(value)) {
							resolve()
						} else {
							reject(new Error('联系电话格式错误'))
						}
					})
				}
			}]
		},
		
	}
	function radioChange(e){
		console.log(e,state.form.serve)
		state.form.serve=e.detail.value
	}
	
	
	
	
	
	async function getInfo(writeType){
		const res =await sheep.$api.commission.giveaway.getUserInfo()
		state.form.agency_name=res.data?.name
		state.form.agency_mobile=res.data?.phone
		console.log('res.data',res.data,writeType)
		if(!res.data&&writeType){
			var userInfo=sheep.$store('user').userInfo
			console.log('userInfo------------',userInfo)
			state.form.agency_name=userInfo?.nickname
			state.form.agency_mobile=userInfo?.mobile
		}
		// state.form.role = sheep.$store('user').userInfo.role;
	}
	
	const handleSave = (url) => {
	  if (['WechatOfficialAccount', 'H5'].includes(sheep.$platform.name)) {
	    sheep.$helper.toast('请长按图片保存');
	    return;
	  }
	  uni.downloadFile({
	    url: url,
	    success:(sres)=> {
	      console.log(sres);
	      uni.saveImageToPhotosAlbum({
	        filePath: sres.tempFilePath,
	        success: (res) => {
	          sheep.$helper.toast('保存成功');
	        },
	        fail: (err) => {
	          sheep.$helper.toast('保存失败');
	          console.log('图片保存失败:', err);
	        },
	      });
	    }
	
	  }).onProgressUpdate((res) => {
	    uni.showLoading({
				title: '正在保存...'
			})
		if (res.progress == 100) {
			uni.hideLoading()
		}
	})
	};
	
	
	const submit = () => {
		console.log(11111,state.form)
		const formSubmit=clone(state.form)
		form.value.validate().then(async formVal => {
			var msg=null
			if(!formSubmit.reverse_card){
				msg='请选择身份证正面'
			}else if(!formSubmit.protrait_card){
				msg='请选择身份证反面'
			}else if(!formSubmit.business_license){
				msg='请选择营业执照'
			}else if(!state.image1){
				msg='请选择店内照片'
			}else if(!state.image2){
				msg='请选择店内照片'
			}else if(!state.image3){
				msg='请选择门头照片'
			}else if(!state.image4){
				msg='请选择收银台照片'
			}
		formSubmit.shop_image=state.image1+','+state.image2+','+state.image3+','+state.image4+(state.image_more?','+state.image_more.join(','):'')
			if(msg){
				uni.showToast({
					title:msg,
					icon: 'none',
					duration: 2000
				})
				return
			}
			
			const res = await sheep.$api.commission.merchant.applyAdd({
				...formSubmit,
				type:1//1入驻 2进件
			})
			if(res.error==0){
				uni.redirectTo({
					url:`/pages/commission/merchant/submit-log?type=${state.type}`
				})
			}else{
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 2000
				})
			}
			
		}).catch(err => {
			console.log('err------',err);
			// uni.showToast({
			// 	title: err[0].errorMessage,
			// 	icon: 'none',
			// 	duration: 2000
			// })
		})
	}

const getDefaultInfo= async()=>{
	const res = await sheep.$api.commission.getDefaultImg()
		console.log(res,'datadatadatadatadata');
		state.form.business_license=res.data.business_license
		state.image1=res.data.img1
		state.image2=res.data.img2
		state.image3=res.data.img3
		state.image4=res.data.img4

}	
	
	onLoad(async(option) => {
		console.log(option,'option');
		getDefaultInfo()
		state.userInfo = sheep.$store('user').userInfo
		// NFC卡进入
		 if(option.bd_no){//刷卡滴过来  只用于鲸囍入驻
		 	uni.setStorageSync('bd_no',option.bd_no)
		 	state.form.serve=3
		 	if(!$store('user').isLogin){//如果未登录
		 	 	showAuthModal();
			}else{//如果已经登录，则去判断是绑卡，还是绑上下级入驻
				card_is_bind(option.bd_no)
			}
			
			return 
		}
		
		if(option.inviteInfo){//填写手机号获取信息进入
			var info=JSON.parse(option.inviteInfo)
			state.form.agency_name=info?.nickname
			state.form.agency_mobile=info?.mobile
		}
		
		state.seeAccount=option.seeAccount
		if(state.seeAccount){//seeAccount  判断是否为查看账号密码
			state.accountInfo=JSON.parse(option.account)
			console.log('state.accountInfo',state.accountInfo)
		}else{//填写表单
			state.type=option.type//0商户自己入驻  1代理商入驻
			state.form.serve=option.shopType
			if(option.type==1){
				getInfo(option.writeType)
			}
		}
		
		
		
		
		
		
		
	})
	// 查询卡是否已绑定-----判断是bd还是商家
	async function card_is_bind(bd_no){
		const res = await sheep.$api.commission.merchant.card_is_bind(bd_no)
		console.log('res',res)
		if(res.error==0){
			if(res.data.available==1){//卡片未绑定
				if(	state.userInfo.extend.max_role==='user'){//---------商户
					uni.showToast({
						title:'该卡还未绑定',
						icon:2000
					})
					await writeInfo()//卡未绑定，查询该用户信息并填入
					return
				}else{//-----------------------------------------------bd
					
					if(state.userInfo.extend.extend_code){
						uni.showToast({
							title:'您已绑定过BD卡',
							icon:2000
						})
						return
					}
					
					uni.showModal({
					    title: '提示',
					    content: '是否要绑定当前卡片',
					    success:async function (res) {
					        if (res.confirm) {
					            await card_bind(bd_no)
					        }
					    }
					});
				}
				
			}else if(res.data.available==0){//卡已绑定-则去绑定上下级关系------下级用
				await bindParent(bd_no)
			}
		}
		
	}
	// 绑定编号接口
	async function card_bind(bd_no){
		const res = await sheep.$api.commission.merchant.card_bind({
			extend_code:bd_no
		})
		if(res.error==0){//绑定成功
			uni.showToast({
				title:'绑定成功',
				duration:2000
			})
		}else{
			uni.showToast({
				title:res.msg,
				icon:'none',
				duration:2000
			})
		}
		
	}
// 绑定上级
	async function bindParent(bd_no){
		const res = await sheep.$api.commission.merchant.bindParent({
			extend_code:bd_no
		})
		if(res.error==0){//未绑定过上下级，绑定成功
			await getProfile()//查询信息获取上级id
			writeInfo()
		}else{//已经绑定过上下级-则查询该人上级信息填入
			uni.showToast({
				title:res.msg,
				icon:'none',
				duration:2000
			})
			writeInfo()
		}
		
	}
	// 获取个人信息
	async function getProfile() {
	  await sheep.$store('user').getInfo()
	}
	
	// 填入代理人信息
	function writeInfo(){
		state.userInfo = sheep.$store('user').userInfo
		state.form.agency_name=state.userInfo.parent_user?.nickname
		state.form.agency_mobile=state.userInfo.parent_user?.mobile
	}
	
	async function loginEnd(e){
		console.log('登录完成拉')
		var bd_no = uni.getStorageSync('bd_no')
		await card_is_bind(bd_no)
	}
	
	function setValue(e,name){
		form.value.setValue(name,e.detail.value);
	}
	
	onUnload(() => {
		
	})
</script>

<style lang="scss" scoped>

	view {
		box-sizing: border-box;
	}
	.btn{
		  width: 702rpx;
		  height: 80rpx;
		  background: #003288;
		  border-radius: 49rpx;
		  font-size: 32rpx;
		  color: #FFFFFF;
	  }
	  .btn2{
		 width: 124rpx;
		 height: 55rpx;
		 line-height: 55rpx;
		 background: #E8F1FF;
		 border-radius: 28rpx;
		 border: 2rpx solid #003288; 
		 font-size: 28rpx;
		 color: #01338A;
	  }
	::v-deep {
		// .radio__inner{
		// 	border-color: #ffdfc7!important;
		// }
		// .radio__inner-icon{
		// 	border-color: #ffdfc7!important;
		// 	background-color:var(--ui-BG-5)!important;
		// }
		.file-picker__box-content{
			border:none!important
		}
		
		.uni-forms-item__inner {
			padding-bottom: 20rpx
		}

		.uni-error-message {
			height: 20rpx;
			display: flex;
		}

		.uni-error-message-text {
			font-size: 20rpx;
			line-height: 1;
		}
	}

	

	


	
	.form-box {
		width: 100%;
		border-radius: 24rpx 24rpx 0 0;
		background: #F8F8F8;
		padding-bottom:60rpx;
		
		position: relative;
		

	}
	.morePic{
		width: 300rpx;
		height:300rpx;
		line-height:300rpx;
		background:#F5F4FC;
		font-size:32rpx;
		text-align: center;
		margin-bottom: 20rpx;
		
	}
	.form-box-input-item-left {
		width: 100%;
		display: flex;
		justify-content: flex-start;
		align-items: center;

		view{
			
		}
	}

	.form-box-input-item {
		display: flex;
		justify-content: flex-end;
		align-items: center;

		input {
			padding-top:12rpx;
			font-size:30rpx;
			text-align: right;
		}
	}

	::v-deep .uni-forms-item__label {
		width:max-content!important;
		.label-text{
			font-size:30rpx;
		}
	}

	::v-deep .uni-forms-item__inner {
		padding-bottom: 0;
		padding-top:20rpx;
		border-bottom: 1rpx solid #F5F5F5;
	}

	
:deep().uni-radio-input{
	margin:0!important
}
	


	.form-box-head-title{
		font-weight: bold;
		font-size: 32rpx;
		color: #323232;
		text-align: left;
		font-style: normal;
	}
	
	.chongwu-zhaopian{
		width:100rpx;
		height:120rpx;
	}
	
</style>